﻿using System;
using System.Windows;
using TodoLister.ViewModels;
using TodoLister.Services;
using TodoLister.Properties;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using TodoLister.Models;
using System.Windows.Threading;
using System.Windows.Controls.Primitives;

namespace TodoLister
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Point startPoint;
        private bool isDragging = false;
        private DispatcherTimer scrollTimer;
        private DateTime lastScrollTime;

        public MainWindow()
        {
            InitializeComponent();
            
            // 在代码中设置DataContext
            var storageService = new XmlFileStorageService("todolist.xml");
            DataContext = new MainViewModel(storageService);

            // 初始化计时器
            scrollTimer = new DispatcherTimer();
            scrollTimer.Interval = TimeSpan.FromSeconds(1);
            scrollTimer.Tick += ScrollTimer_Tick;
        }

        /// <summary>
        /// 处理鼠标移动事件，实现拖拽功能
        /// </summary>
        private void ListBox_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && !isDragging)
            {
                Point position = e.GetPosition(null);
                
                if (Math.Abs(position.X - startPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(position.Y - startPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    StartDrag(e);
                }
            }
        }

        /// <summary>
        /// 开始拖拽操作
        /// </summary>
        private void StartDrag(MouseEventArgs e)
        {
            isDragging = true;
            ListBox listBox = e.Source as ListBox;
            ListBoxItem listBoxItem = FindAncestor<ListBoxItem>((DependencyObject)e.OriginalSource);

            if (listBoxItem != null)
            {
                DragDrop.DoDragDrop(listBoxItem, listBoxItem.DataContext, DragDropEffects.Move);
            }

            isDragging = false;
        }

        /// <summary>
        /// 处理拖拽进入事件
        /// </summary>
        private void ListBox_DragEnter(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(TodoItem)))
            {
                e.Effects = DragDropEffects.None;
            }
        }

        /// <summary>
        /// 处理拖放完成事件
        /// </summary>
        private void ListBox_Drop(object sender, DragEventArgs e)
        {
            if (sender is ListBox listBox)
            {
                Point dropPoint = e.GetPosition(listBox);
                object data = e.Data.GetData(typeof(TodoItem));
                
                if (data is TodoItem sourceItem)
                {
                    var targetItem = ((FrameworkElement)e.OriginalSource).DataContext as TodoItem;
                    
                    if (targetItem != null && !ReferenceEquals(sourceItem, targetItem))
                    {
                        var viewModel = (MainViewModel)DataContext;
                        viewModel.ReorderItems(sourceItem, targetItem);
                    }
                }
            }
        }

        /// <summary>
        /// 查找指定类型的父元素
        /// </summary>
        private static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
        {
            do
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            while (current != null);
            return null;
        }

        /// <summary>
        /// 处理鼠标按下事件
        /// </summary>
        private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            startPoint = e.GetPosition(null);
        }

        /// <summary>
        /// 窗口加载事件处理
        /// </summary>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 设置窗口位置
            if (Settings.Default.WindowLeft >= 0)
            {
                Left = Settings.Default.WindowLeft;
            }
            if (Settings.Default.WindowTop >= 0)
            {
                Top = Settings.Default.WindowTop;
            }
        }

        /// <summary>
        /// 窗口关闭事件处理
        /// </summary>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // 保存窗口位置
            Settings.Default.WindowLeft = Left;
            Settings.Default.WindowTop = Top;
            Settings.Default.Save();

            // 保存待办事项列表
            if (DataContext is MainViewModel viewModel)
            {
                viewModel.SaveItemsCommand.Execute(null);
            }
        }

        /// <summary>
        /// 处理滚动事件
        /// </summary>
        private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (sender is ScrollViewer scrollViewer)
            {
                // 如果发生了垂直滚动
                if (e.VerticalChange != 0)
                {
                    lastScrollTime = DateTime.Now;
                    
                    // 显示滚动条
                    if (scrollViewer.Template.FindName("PART_VerticalScrollBar", scrollViewer) is ScrollBar scrollBar)
                    {
                        scrollBar.Visibility = Visibility.Visible;
                    }

                    // 确保计时器在运行
                    if (!scrollTimer.IsEnabled)
                    {
                        scrollTimer.Start();
                    }
                }
            }
        }

        /// <summary>
        /// 计时器事件处理
        /// </summary>
        private void ScrollTimer_Tick(object sender, EventArgs e)
        {
            var currentTime = DateTime.Now;
            var timeSinceLastScroll = currentTime - lastScrollTime;

            // 如果超过5秒没有滚动
            if (timeSinceLastScroll.TotalSeconds >= 5)
            {
                // 查找当前ListBox中的ScrollViewer
                var listBox = this.FindName("TodoListBox") as ListBox;
                if (listBox != null)
                {
                    var scrollViewer = GetScrollViewer(listBox);
                    if (scrollViewer != null)
                    {
                        // 隐藏滚动条
                        if (scrollViewer.Template.FindName("PART_VerticalScrollBar", scrollViewer) is ScrollBar scrollBar)
                        {
                            scrollBar.Visibility = Visibility.Hidden;
                        }
                    }
                }
                
                // 停止计时器
                scrollTimer.Stop();
            }
        }

        /// <summary>
        /// 获取控件中的ScrollViewer
        /// </summary>
        private ScrollViewer GetScrollViewer(DependencyObject element)
        {
            if (element is ScrollViewer)
                return element as ScrollViewer;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                var child = VisualTreeHelper.GetChild(element, i);
                var result = GetScrollViewer(child);
                if (result != null)
                    return result;
            }
            return null;
        }
    }
}
